import {PlusOutlined} from '@ant-design/icons';
import {Button, message, Input, Drawer, Steps, Modal} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {useIntl, FormattedMessage, request} from 'umi';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable, {EditableProTable} from '@ant-design/pro-table';
import ReactJson from 'react-json-view'

import ProForm, {
  ProFormGroup,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormUploadButton
} from '@ant-design/pro-form';
import {createDo} from '@/services/doa/repo'

import ProCard from "@ant-design/pro-card";

const {Step} = Steps

//{"id":"","type":"0.TYPE/DO","attributes":{"title":"sam发推：什么时候由媒体来宣布下任总统了？","source":"环球网","publishTime":"2020-11-09 06:46","url":"https://world.huanqiu.com/article/40cnJsElNVt","metadata":{"标题":"柳熠发推：什么时候由媒体来宣布下任总统了？","来源":"环球网","分类":"新闻"}},"elements":[{"id":"test","length":"3","dataString":"aaa","attributes":{"attr":"bbb"}}]}
const DoWithAPIValueCreate = () => {

  const [current, setCurrent] = useState(0)
  const next = () => {
    setCurrent(current + 1)
  }
  const prev = () => {
    setCurrent(current - 1)
  }

  const meta = [
    {"key": "title", "desc": "数字对象名称（title)"},
    {"key": "description", "desc": "数字对象描述（description)"},
    {"key": "type", "desc": "数字对象分类（type)"},
    {"key": "date", "desc": "创建时间（date)"},
    {"key": "format", "desc": "格式（format)"},
    {"key": "language", "desc": "语言（language)"},
    {"key": "source", "desc": "来源（source）"},
    {"key": "topic", "desc": "主题（topic)"},
    {"key": "coverage", "desc": "范围（coverage)"}
  ]

  const info = (msg) => {
    message.info(msg);
  };


  const defaultMetaDo = meta.map((value, index) => {
    return {
      id: index.toString(),
      key: value.key,
      desc: value.desc,
      value: "",
    }
  })


  const updateMetadata = () => {
    const metadata = {}
    for (const item in dataSource) {
      metadata[dataSource[item]?.key] = dataSource[item]?.value
    }
    setAttributes({...attributes, metadata: metadata})
  }


  const doRef = useRef();


  const createDigitalObject = () => {
    console.log(doInfo)
    createDo(JSON.stringify(doInfo)).then((response) => {
      console.log(response)
      if (response.success) {
        info("创建成功！")
      } else {
        info("创建失败！")
      }
    })
  }


  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const intl = useIntl();

  const [editableKeys, setEditableRowKeys] = useState(() =>
    defaultMetaDo.map((item) => item.id),
  );

  const [dataSource, setDataSource] = useState(() => defaultMetaDo);
  const [elements, setElements] = useState([])

  const [editableEleKeys, setEditableEleKeys] = useState(() =>
    elements.map((item) => item.id),
  );

  const [attributes, setAttributes] = useState({
      "title": "sam发推：什么时候由媒体来宣布下任总统了？",
      "source": "环球网",
      "publishTime": "2020-11-09 06:46",
      "url": "https://world.huanqiu.com/article/40cnJsElNVt",
      "metadata": {}
    }
  )

  const [doInfo, setDoInfo] = useState({
    "id": "",
    "type": "0.TYPE/DO",
    "attributes": attributes,
    "elements": elements
  })

  useEffect(() => {
    doInfo.attributes = attributes
    setDoInfo(doInfo)
  }, [attributes])


  const columns = [
    {
      title: '元数据字段键值',
      key: 'key',
      dataIndex: 'key',
      editable: (text, record, index) => {
        return index > 8;
      },
    },
    {
      title: '元数据字段描述',
      dataIndex: 'desc',
      width: '30%',
      editable: (text, record, index) => {
        return index > 8;
      },
      formItemProps: {
        rules: [
          {
            required: true,
            whitespace: true,
            message: '此项是必填项',
          }
        ],
      },
    },
    {
      title: '元数据值',
      key: 'value',
      dataIndex: 'value',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 250,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            setElements(elements.filter((item) => item.id !== record.id));
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  const elementColumns = [
    {
      title: '序号',
      dataIndex: 'id',
      valueType: 'indexBorder',
      editable: (text, record, index) => {
        return false;
      },
    },
    {
      title: '类型',
      key: 'type',
      dataIndex: 'type',
      valueType: 'select',
      valueEnum: {
        string: {
          text: '字符串',
          status: 'string'
        },
        api: {
          text: 'API',
          status: 'api',
        },
        file: {
          text: '文件',
          status: 'file',
        }
      },
      editable: (text, record, index) => {
        return true;
      },
    },
    {
      title: '属性',
      key: 'attributes',
      dataIndex: 'attributes',
      width: '30%',
      editable: (text, record, index) => {
        return true;
      },
      formItemProps: {
        rules: [
          {
            whitespace: true,
            message: '请输入JSON格式的属性，如无可不输入',
          }
        ],
      },
    },
    {
      title: '值/示例',
      key: 'dataString',
      dataIndex: 'dataString',
      width: '30%',
      editable: (text, record, index) => {
        return true;
      },
      formItemProps: {
        rules: [
          {
            required: true,
            whitespace: true,
            message: '此项是必填项',
          }
        ],
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 250,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            setDataSource(dataSource.filter((item) => item.id !== record.id));
          }}
        >
          删除
        </a>,
        <EditableProTable.RecordCreator
          record={{
            ...record,
          }}
        >
          <a>复制此行到末尾</a>
        </EditableProTable.RecordCreator>,
      ],
    },
  ];

  const [showDetail, setShowDetail] = useState(false)
  const [showFileEditor, setShowFileEditor] = useState(false);

  const [fileAddress,setFileAddress] = useState("");


  const uploadMonitor = (file) =>{
    console.log(file)
    if(file?.file?.status === 'done'){
      const res = file?.file?.response
      const fileDownloadUri = res?.fileDownloadUri
      if(fileDownloadUri != null){
        setFileAddress("上传成功，请复制文件地址:\n" + fileDownloadUri)
      }
    }
  }

  return (
    <PageContainer>

      <ProCard layout="center" style={{"margin-bottom": "20px"}}>
        <Steps current={current}>
          <Step title="DO属性输入" description=""/>
          <Step title="元素配置和输入" description=""/>
          <Step title="元数据输入" description=""/>
        </Steps>

        {current < 2 && (
          <Button type="primary" onClick={() => next()}>
            下一步
          </Button>
        )}
        {current === 2 && (
          <Button type="primary" onClick={() => createDigitalObject()}>
            完成
          </Button>
        )}
        {current > 0 && (
          <Button style={{margin: '0 8px'}} onClick={() => prev()}>
            上一步
          </Button>
        )}

        <Button style={{margin: '0 8px'}} onClick={() => setShowDetail(true)}>
          预览
        </Button>
      </ProCard>

      <ProCard layout="center" title={"完成DO的属性信息输入"}
               style={{"margin-bottom": "20px", display: current != 0 ? 'none' : ''}}>

        <ProCard colSpan={{xs: 2, sm: 4, md: 6, lg: 8, xl: 10}}>
          <ProForm
            onSubmit={(values) => {
              console.log("==save attributes====")
              setAttributes({...JSON.parse(values.attributes), metadata: attributes?.metadata})
            }}
            onValuesChange={(_, values) => {
              console.log(values)
              setAttributes({...JSON.parse(values.attributes), metadata: attributes?.metadata})
            }}
            submitter={{
              // 配置按钮文本
              searchConfig: {
                resetText: '重置',
                submitText: '保存',
              },
            }}
            initialValues={
              {
                "attributes": JSON.stringify(attributes)
              }
            }
          >
            <ProFormTextArea placeholder="请输入DO的属性信息" allowClear name="attributes"/>
          </ProForm>
        </ProCard>
        <ProCard title={"预览"} colSpan={{xs: 2, sm: 4, md: 6, lg: 8, xl: 10}}>
          <ReactJson src={attributes}/>
        </ProCard>
      </ProCard>

      <ProCard title={"完成元素配置和输入"} style={{"margin-bottom": "20px", display: current != 1 ? 'none' : ''}}>
        <EditableProTable
          headerTitle="请输入Element信息"
          columns={elementColumns}
          rowKey="id"
          value={elements}
          onChange={setElements}
          recordCreatorProps={{
            newRecordType: 'dataSource',
            record: () => ({
              id: elements.length + 1,
            }),
          }}
          toolBarRender={() => {
            return [
              <Button
                type="primary"
                key="save"
                onClick={() => {
                  doInfo.elements = elements.map((item, index) => {
                    if ("api" === item.type) {
                      //API类型的时候需要配置url和method方法，已经参数，目前简化就get请求+url，不支持参数
                      return {
                        id: item.id,
                        dataString: item.dataString,
                        type: "string",
                        attributes: item.attributes === "" ? {} : {...JSON.parse(item.attributes), api: true}
                      }
                    } else
                      return {
                        id: item.id,
                        dataString: item.dataString,
                        type: item.type,
                        attributes: item.attributes === "" ? {} : JSON.parse(item.attributes)
                      }
                  })
                  setDoInfo(doInfo)
                }}
              >
                保存数据
              </Button>,
              <Button
                type="primary"
                key="upload"
                onClick={()=>{
                  setShowFileEditor(true)
                }}
              >
                上传文件
              </Button>
            ];
          }}
          editable={{
            type: 'multiple',
            editableEleKeys,
            actionRender: (row, config, defaultDoms) => {
              return [defaultDoms.delete];
            },
            onValuesChange: (record, recordList) => {
              console.log(record)
              console.log(recordList)
              setElements(recordList);
            },
            onChange: setEditableEleKeys,
          }}
        />
      </ProCard>

      <ProCard style={{"margin-bottom": "20px", display: current != 2 ? 'none' : ''}}>
        <EditableProTable
          headerTitle="请输入DO元信息"
          columns={columns}
          rowKey="id"
          value={dataSource}
          onChange={setDataSource}
          recordCreatorProps={{
            newRecordType: 'dataSource',
            record: () => ({
              id: "" + (dataSource.length + 1),
            }),
          }}
          toolBarRender={() => {
            return [
              <Button
                type="primary"
                key="save"
                onClick={() => {
                  // dataSource 就是当前数据，可以调用 api 将其保存
                  console.log(dataSource);
                  updateMetadata()
                }}
              >
                保存数据
              </Button>,
            ];
          }}
          editable={{
            type: 'multiple',
            editableKeys,
            actionRender: (row, config, defaultDoms) => {
              return [defaultDoms.delete];
            },
            onValuesChange: (record, recordList) => {
              console.log(record)
              console.log(recordList)
              setDataSource(recordList);
            },
            onChange: setEditableRowKeys,
          }}
        />
      </ProCard>

      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setShowDetail(false);
        }}
        closable={false}
      >
        <ReactJson src={doInfo}/>
      </Drawer>

      <Modal title="上传文件并获取访问地址"
             visible={showFileEditor}
             onOk={() => {setShowFileEditor(false);setFileAddress("")}}
             onCancel={() => {setShowFileEditor(false);setFileAddress("")}}
      >
        <ProForm submitter={false}
          onValuesChange={(changeValues) => {
          }}
        >
          <ProFormUploadButton
            name="file"
            label="上传文件"
            max={1}
            fieldProps={{
              name: 'file',
              listType: 'text',
            }}
            onChange={(file)=>{uploadMonitor(file)}}
            beforeUpload={(file) => {
            }}
            action="http://localhost:8080/doa/repo/uploadFile"
          />
        </ProForm>
        {fileAddress}
      </Modal>

    </PageContainer>
  );
};

export default DoWithAPIValueCreate;

